package logic

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	cache "tiktok/model/redis"
	"tiktok/pkg"
	"tiktok/tiktokrpc/internal/svc"
	"tiktok/tiktokrpc/tiktokrpc"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *tiktokrpc.SendSmsRequest) (*tiktokrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.Redis.Get(l.ctx, "sendSmsErr"+in.Mobile)
	if get.Val() == "1" {
		return nil, fmt.Errorf("短信只允许五分钟发送一次")
	}
	intn := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(intn))
	if err != nil {
		return nil, err
	}
	if *sms.Body.Code != "OK" {
		return nil, fmt.Errorf(*sms.Body.Message)
	}
	cache.Redis.Set(l.ctx, "sendSms"+in.Mobile, intn, time.Minute*3)

	cache.Redis.Incr(l.ctx, "sendSmsErr"+in.Mobile)
	cache.Redis.Expire(l.ctx, "sendSmsErr"+in.Mobile, time.Minute*5)
	
	return &tiktokrpc.SendSmsResponse{}, nil
}
